#include <zmq.h>
#include <stdio.h>
#include <string.h>

//#define COMM_URL "tcp://127.0.0.1:5555"
#define COMM_URL "inproc://lat_test"

void dump_msg(const void* data, int size)
{
    unsigned char* ptr = (unsigned char*)data;
    printf("[%03d] ", size);
    int i = 0;
    //for (i = 0; i < size; i++)
    //    printf("%02X", ptr[i]);
    printf("%.*s\r\n", size, ptr);
}

void dump_address(const void* data, int size)
{
    unsigned char* ptr = (unsigned char*)data;
    printf("[%03d] ", size);
    int i = 0;
    //for (i = 0; i < size; i++)
    //    printf("%02X", ptr[i]);
    
    printf("%.*s\r\n", size, ptr);
    printf("\n");
}

void dealer_main(void* arg)
{
    //void* context = zmq_ctx_new();
    void* context = arg;
    void* dealer = zmq_socket(context, ZMQ_DEALER);
    zmq_setsockopt(dealer, ZMQ_ROUTING_ID, "S100", 4);

    zmq_connect(dealer, COMM_URL);


    int ret;
    char buf[256] = "hello";
    int total = 10000;
    void* watch;
    
    watch = zmq_stopwatch_start();
    while (total)
    {
        strcpy(buf, "hello");
        /*发送一帧，不需要发送地址帧*/
        zmq_send(dealer, buf, strlen(buf), 0);
        //zmq_sleep(1);
        /*接收一帧，不会接收到地址帧*/
        ret = zmq_recv(dealer, buf, sizeof(buf), 0);
        //dump_msg(buf, ret);
        total--;
    }
    unsigned long usconsume = zmq_stopwatch_stop(watch);
    printf("time consumed %ld\r\n", usconsume);

    zmq_close(dealer);
    zmq_ctx_destroy(context);
}

int main(void)
{
    void* context = zmq_ctx_new();
    void* router = zmq_socket(context, ZMQ_ROUTER);
    //zmq_bind(router, "tcp://*:5555");
    zmq_bind(router, COMM_URL);

    zmq_threadstart(dealer_main, context);

    int ret;
    zmq_msg_t address;
    zmq_msg_t data;
    while (1)
    {
        zmq_msg_init(&address);
        zmq_msg_init(&data);
        /*接收到的第一帧表示对端的地址*/
        ret = zmq_msg_recv(&address, router, 0);
        dump_address(zmq_msg_data(&address), ret);

        /*从第二帧开始才是对端发来的消息*/
        ret = zmq_msg_recv(&data, router, 0);
        //dump_msg(zmq_msg_data(&data), ret);

        /*发送的时候，先发一帧对端的地址*/
        zmq_msg_send(&address, router, ZMQ_SNDMORE);
        /*然后再发送给对端消息*/
        memcpy(zmq_msg_data(&data), "world", strlen("world"));
        zmq_msg_send(&data, router, 0);

        zmq_msg_close(&address);
        zmq_msg_close(&data);
    }
    zmq_close(router);
    zmq_ctx_destroy(context);
    return 0;
}